package com.ewhale.feitengguest.ui.user.mine

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.core.content.ContextCompat
import butterknife.OnClick
import cn.jiguang.share.android.api.JShareInterface
import cn.jiguang.share.android.api.PlatActionListener
import cn.jiguang.share.android.api.Platform
import cn.jiguang.share.android.api.ShareParams
import cn.jiguang.share.qqmodel.QQ
import cn.jiguang.share.wechat.Wechat
import cn.jiguang.share.wechat.WechatMoments
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.app.AppApplication
import com.ewhale.feitengguest.dto.ArticleDetailDto
import com.ewhale.feitengguest.dto.BalanceDto
import com.ewhale.feitengguest.dto.LoginInfoDto
import com.ewhale.feitengguest.dto.RankDto
import com.ewhale.feitengguest.presenter.user.mine.InvitePresenter
import com.ewhale.feitengguest.ui.WebViewActivity
import com.ewhale.feitengguest.utils.GlideImageLoader
import com.ewhale.feitengguest.view.user.mine.InviteView
import com.orhanobut.hawk.Hawk
import com.simga.library.activity.MBaseActivity
import com.simga.library.utils.*
import com.uuzuche.lib_zxing.activity.CodeUtils
import kotlinx.android.synthetic.main.activity_invite.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList

class InviteActivity : MBaseActivity<InvitePresenter?>(), InviteView {


    private var infoDto: LoginInfoDto? = null
    private var shareUrl: String? = null
    var ImagePath: String? = null

    private val imageUrl: MutableList<String?> = ArrayList()
    override fun getViewId(): Int {
        return R.layout.activity_invite
    }

    @SuppressLint("SetTextI18n")
    override fun init(savedInstanceState: Bundle?) {
        setTitle("邀请好友")
        mTvRight.text = "收徒规则"
        mTvRight.setTextColor(ContextCompat.getColor(mContext, R.color.main_color))
        mTvRight.visibility = View.VISIBLE
        infoDto = Hawk.get<LoginInfoDto?>(HawkKey.USER_LOGIN_INFO, null)
        tv_invite!!.text = "我的邀请码 : " + infoDto!!.recommendCode
        //生成二维码图片
        shareUrl = "https://app.9688app.com/ftzk-share?recommendCode=" + infoDto!!.recommendCode
        iv_QRCode!!.setImageBitmap(CodeUtils.createImage(shareUrl, 340, 340, null))
        //请求佣金数据
        presenter!!.loadBalance()
        //显示跑马灯
        val dto = Hawk.get<RankDto?>(HawkKey.RANKING, null)
        if (dto != null) {
            val messages = ArrayList<String>()
            for (str in dto.rankingDto) {
                messages.add(str.nickName + "    邀请了" + str.recommendNum + "人    累计获得" + str.commission + "佣金")
            }
            marqueeView!!.startWithList(messages as List<Nothing>?)
        }
        imageUrl.add(Hawk.get(HawkKey.BANNER_IMAGE, ""))
        bannerlayout!!.run {
            setImageLoader(GlideImageLoader())
            setImages(imageUrl)
            start()
        }
    }

    public override fun onStart() {
        super.onStart()
        marqueeView!!.startFlipping()
    }

    public override fun onStop() {
        super.onStop()
        marqueeView!!.stopFlipping()
    }

    override fun onResume() {
        super.onResume()
        //把asset的图片复制到本地
        if (CheckUtil.isNull(ImagePath)) {
            object : Thread() {
                override fun run() {
                    super.run()
                    val imageFile = copyResurces("icon_logo.png", "icon_share.png", 0)
                    if (imageFile != null) {
                        ImagePath = imageFile.absolutePath
                    }
                }
            }.start()
        }
    }

    override fun isUseBaseTitleBar(): Boolean {
        return true
    }

    override fun initListener() {
        mTvRight.setOnClickListener { presenter!!.loadArticleDetails(10) }
        bannerlayout!!.setOnBannerListener { InviteListActivity.open(mContext) }
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String, message: String) {
        showErrorMsg(code, message)
    }

    override fun showBalance(result: BalanceDto) {
        tv_invite_num!!.text = result.recommendNum.toString()
        tv_invite_num_jianjie!!.text = result.indirectRecommendNum.toString()
        tv_price!!.text = StringUtil.to2Decimal(StringUtil.to2Double(result.commission))
    }

    override fun showDetail(result: ArticleDetailDto) {
        WebViewActivity.open(mContext, "收徒规则", result.content)
    }

    override fun showRanking(list: RankDto) {}
    override fun showLastRanking(result: String) {}

    @OnClick(R.id.ll_handle, R.id.iv_share_wechat, R.id.iv_share_qq, R.id.ll_invite, R.id.ll_yongjin)
    fun onViewClicked(view: View) {
        val shareParams = ShareParams()
        when (view.id) {
            R.id.ll_handle -> {
                if (infoDto == null) return
                if (copy(infoDto!!.recommendCode)) {
                    showToast("邀请码已复制到剪切板")
                }
            }
            R.id.iv_share_wechat -> {
                shareParams.apply {
                    shareType = Platform.SHARE_WEBPAGE
                    title = resources.getString(R.string.app_name)
                    text = if (infoDto == null) "加入飞腾赚客，完成任务获取佣金!" else "加入飞腾赚客，完成任务获取佣金!我的邀请码" + infoDto!!.recommendCode
                    url = shareUrl
                    imagePath = ImagePath
                    JShareInterface.share(Wechat.Name, shareParams, mPlatActionListener)
                }
            }
            R.id.iv_share_qq -> {
                shareParams.apply {
                    shareType = Platform.SHARE_WEBPAGE
                    title = resources.getString(R.string.app_name)
                    text = if (infoDto == null) "加入飞腾赚客，完成任务获取佣金!" else "加入飞腾赚客，完成任务获取佣金!我的邀请码" + infoDto!!.recommendCode
                    url = shareUrl
                    imagePath = ImagePath
                    JShareInterface.share(QQ.Name, shareParams, mPlatActionListener)
                }
            }
            R.id.ll_invite -> {
                AppApplication.Jump_invite_list = true
                sendBroadcast(Intent("JUMP_INVITE_LIST"))
                finish()
            }
            R.id.ll_yongjin -> {
                //                int status = Hawk.get(HawkKey.USER_AUTH_STATUS, 0);
                MyWalletActivity.open(mContext)
                finish()
            }
        }
    }

    private fun copyResurces(src: String, dest: String, flag: Int): File? {
        var filesDir: File? = null
        try {
            if (flag == 0) { //copy to sdcard
                filesDir = File(SdCardUtil.DEFAULT_PHOTO_PATH + dest)
                val parentDir = filesDir.parentFile
                if (!parentDir.exists()) {
                    parentDir.mkdirs()
                }
            } else { //copy to data
                filesDir = File(getFilesDir(), dest)
            }
            if (!filesDir.exists()) {
                filesDir.createNewFile()
                val open = assets.open(src)
                val fileOutputStream = FileOutputStream(filesDir)
                val buffer = ByteArray(4 * 1024)
                var len = 0
                while (open.read(buffer).also { len = it } != -1) {
                    fileOutputStream.write(buffer, 0, len)
                }
                open.close()
                fileOutputStream.close()
            }
        } catch (e: IOException) {
            e.printStackTrace()
            if (flag == 0) {
                filesDir = copyResurces(src, dest, 1)
            }
        }
        return filesDir
    }

    private val mPlatActionListener: PlatActionListener = object : PlatActionListener {
        override fun onComplete(platform: Platform, action: Int, data: HashMap<String, Any>) {
            if (handler != null) {
                if (platform.name == Wechat.Name || platform.name == WechatMoments.Name) return
                val message = handler.obtainMessage()
                message.obj = "分享成功"
                handler.sendMessage(message)
            }
        }

        override fun onError(platform: Platform, action: Int, errorCode: Int, error: Throwable) {
            LogUtil.e("JIA", "分享失败:" + (error.message) + "---" + errorCode)
            if (handler != null) {
                val message = handler.obtainMessage()
                message.obj = "分享失败"
                handler.sendMessage(message)
            }
        }

        override fun onCancel(platform: Platform, action: Int) {
            if (handler != null) {
                val message = handler.obtainMessage()
                message.obj = "分享取消"
                handler.sendMessage(message)
            }
        }
    }
    private val handler: Handler? = object : Handler() {
        override fun handleMessage(msg: Message) {
            val toastMsg = msg.obj as String
            //            showToast(toastMsg);
        }
    }

    companion object {
        @JvmStatic
        fun open(context: MBaseActivity<*>) {
            context.startActivity(null, InviteActivity::class.java)
        }
    }
}